<template>
  <el-dialog v-model="dialogVisible" title="主监控点管理" width="920px" :before-close="handleClose"
    class="video-manage-dialog" destroy-on-close :close-on-click-modal="false" :close-on-press-escape="false"
    :z-index="10001">
    <div class="search-bar">
      <div>
        <el-input v-model="searchQuery" placeholder="输入监控点或所属机构名称过滤" class="search-input" clearable
          style="--el-text-color-placeholder: rgb(40, 136, 238);--el-text-color-regular: rgb(40, 136, 238);">
        </el-input>
        <!-- 查询 -->
        <el-button type="primary" @click="handleSearch"
          style="
            margin-left: 10px;
            --el-button-bg-color: rgb(40, 136, 238);
            --el-button-border-color: rgb(40, 136, 238);
            --el-button-hover-bg-color: rgb(40, 136, 238);
            --el-button-hover-border-color: rgb(40, 136, 238);
            --el-button-active-bg-color: rgb(40, 136, 238);
          ">搜索
          <el-icon style="margin-left: 3px;">
            <Search />
          </el-icon>
        </el-button>
      </div>
      <!-- 新增 -->
      <el-button type="primary" @click="handleAdd"
        style="
          --el-button-bg-color: rgb(40, 136, 238);
          --el-button-border-color: rgb(40, 136, 238);
          --el-button-hover-bg-color: rgb(40, 136, 238);
          --el-button-hover-border-color: rgb(40, 136, 238);
          --el-button-active-bg-color: rgb(40, 136, 238);
        ">
        <el-icon>
          <Plus />
        </el-icon>新增监控点
      </el-button>
    </div>

    <!-- 使用el-Scrollbar优化滚动体验 -->
    <div class="draggable-outer-container" v-loading="loading">
      <el-scrollbar height="550px" class="custom-scrollbar">
        <div class="draggable-list">
          <div 
            v-for="(element, index) in displayData" 
            :key="element.ObjectId"
            class="draggable-item"
            :class="{'dragging': isDragging === index, 'disabled': isSorting}"
            draggable="true"
            @dragstart="handleNativeDragStart($event, index)"
            @dragover.prevent="handleNativeDragOver($event, index)"
            @dragenter.prevent
            @drop="handleNativeDrop($event, index)"
          >
            <div class="item-content">
              <div class="drag-handle">
                <el-icon><Rank /></el-icon>
              </div>
              <div class="item-index">{{ index + 1 }}</div>
              <div class="item-name">{{ element.ChannelName }}</div>
              <div class="item-org">{{ element.ChannelOrgName }}</div>
              <div class="item-actions">
                <el-button size="small" type="danger" link @click="handleDelete(element)" :disabled="isSorting">
                  <el-icon style="color: rgba(255, 255, 255, 0.8);">
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 排序中提示覆盖层 -->
        <div class="sorting-overlay" v-if="isSorting">
          <el-icon class="sorting-icon"><Loading /></el-icon>
          <span>排序更新中...</span>
        </div>
      </el-scrollbar>
    </div>
    <div class="total-text">共{{ displayData.length }}条</div>

    <!-- 新增/编辑表单对话框 -->
    <el-dialog v-model="formDialogVisible" :title="isEdit ? '编辑监控点' : '新增监控点'" width="520px" top="25vh" append-to-body
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px" style="margin-top: 10px;">
        <el-form-item label="所属机构" prop="OrgId">
          <el-select v-model="form.OrgId" placeholder="请选择所属机构" filterable @change="handleOrgChange"
            style="
              width: 100%;
              --el-text-color-placeholder: rgb(40, 136, 238);
              --el-text-color-regular: rgb(40, 136, 238);
              --el-fill-color-light: rgb(40, 136, 238);
              ">
            <el-option v-for="item in orgOptions" :key="item.ObjectId" :label="item.ClientName" :value="item.ObjectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="监控点" prop="ChannelId">
          <el-select v-model="form.ChannelId" placeholder="请选择监控点" filterable @change="handleChannelChange"
            style="
              --el-text-color-placeholder: rgb(40, 136, 238);
              --el-text-color-regular: rgb(40, 136, 238);
              --el-fill-color-light: rgb(40, 136, 238);
              ">
            <el-option v-for="item in filteredChannelOptions" :key="item.ObjectId" :label="item.ChannelName" :value="item.ObjectId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" style="
            --el-button-bg-color: rgb(40, 136, 238);
            --el-button-border-color: rgb(40, 136, 238);
            --el-button-hover-bg-color: rgb(40, 136, 238);
            --el-button-hover-border-color: rgb(40, 136, 238);
            --el-button-active-bg-color: rgb(40, 136, 238);
          ">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete, Rank, Loading } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { getHomeCameraList, getChannelList, queryChildrenOrgList, addHomeCamera, deleteHomeCamera, updateHomeCameraOrder } from '@/api/h3yun'
import { useUserStore } from '@/store/userStore'

interface VideoPoint {
  ObjectId: string
  ChannelName: string
  ChannelOrgName: string
}

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits(['update:modelValue', 'refresh'])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const searchQuery = ref('')
const tableData = ref<VideoPoint[]>([])
// 用于显示和拖拽的数据，这不是计算属性
const displayData = ref<VideoPoint[]>([])
const formDialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const channelOptions = ref<any[]>([])
const orgOptions = ref<any[]>([])
const allChannelOptions = ref<any[]>([])
const userStore = useUserStore()
const powerCode = computed(() => userStore.userInfo?.powerCode)
const loading = ref(false)
const isDragging = ref(-1)
const isSorting = ref(false) // 标记是否正在提交排序

watch(dialogVisible, (newVal) => {
  if (newVal) {
    initHomeCameraList()
  }
})

watch(formDialogVisible, (newVal) => {
  if (newVal) {
    // 获取监控点列表
    getChannelList().then(res => {
      console.log(res, '==监控点列表==')
      allChannelOptions.value = res.data
      channelOptions.value = res.data
    })
    
    // 获取组织机构列表
    queryChildrenOrgList().then(res => {
      console.log(res, '==组织机构列表==')
      orgOptions.value = res.data
    })
  }
})

// 监听搜索关键词变化，更新显示数据
watch(searchQuery, (newVal) => {
  updateDisplayData()
})

// 更新显示数据
const updateDisplayData = () => {
  if (searchQuery.value) {
    displayData.value = tableData.value.filter(item =>
      item.ChannelName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
      item.ChannelOrgName.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  } else {
    displayData.value = [...tableData.value]
  }
}

const initHomeCameraList = () => {
  loading.value = true
  getHomeCameraList().then(res => {
    console.log(res, '==res==')
    //根据OrgId排序
    tableData.value = res.data.sort((a, b) => a.sortVal - b.sortVal)
    updateDisplayData() // 更新显示数据
    loading.value = false
  }).catch(() => {
    loading.value = false
    ElMessage.error('获取监控点列表失败')
  })
}

const form = ref({
  ChannelId: undefined,
  OrgId: undefined,
})

// 根据所选机构过滤监控点选项
const filteredChannelOptions = computed(() => {
  if (!form.value.OrgId) {
    return allChannelOptions.value
  }
  return allChannelOptions.value.filter(item => item.OrgId === form.value.OrgId)
})

const handleOrgChange = (newVal: any) => {
  // 重置监控点选择
  form.value.ChannelId = undefined
}

const handleChannelChange = (newVal: any) => {
  // 如果选择了监控点，但未选择机构，自动设置机构
  if (newVal && !form.value.OrgId) {
    const channelInfo = allChannelOptions.value.find(item => item.ChannelId === newVal)
    if (channelInfo && channelInfo.OrgId) {
      form.value.OrgId = channelInfo.OrgId
    }
  }
}

const rules = {
  OrgId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
  ChannelId: [{ required: true, message: '请选择监控点', trigger: 'change' }],
}

const handleClose = () => {
  dialogVisible.value = false
  emit('refresh')
}

const handleSearch = () => {
  initHomeCameraList()
}

const handleAdd = () => {
  isEdit.value = false
  form.value = {
    ChannelId: undefined,
    OrgId: undefined,
  }
  formDialogVisible.value = true
}

const handleDelete = (row: VideoPoint) => {
  ElMessageBox.confirm('确认删除该监控点吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实现删除逻辑
    deleteHomeCamera({ObjectId: row.ObjectId}).then(res => {
      console.log(res, '==deleteHomeCamera==')
      ElMessage.success('删除成功')
      initHomeCameraList()
    })
  })
}

// 处理拖拽开始事件
const handleDragStart = (evt) => {
  // 如果正在排序中，禁止拖拽
  if (isSorting.value) {
    evt.preventDefault();
    return;
  }
  const { oldIndex } = evt;
  isDragging.value = oldIndex;
  console.log('开始拖拽', oldIndex);
}

// 原生拖放API实现
const dragItemIndex = ref<number | null>(null)

const handleNativeDragStart = (event: DragEvent, index: number) => {
  if (isSorting.value) {
    event.preventDefault()
    return
  }
  dragItemIndex.value = index
  event.dataTransfer?.setData('text/plain', index.toString())
  event.dataTransfer!.effectAllowed = 'move'
  isDragging.value = index
}

const handleNativeDragOver = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (dragItemIndex.value === null || dragItemIndex.value === index) return
  event.dataTransfer!.dropEffect = 'move'
}

const handleNativeDrop = (event: DragEvent, index: number) => {
  event.preventDefault()
  if (dragItemIndex.value === null || dragItemIndex.value === index) return
  
  // 交换数组元素位置
  const newData = [...displayData.value]
  const [removed] = newData.splice(dragItemIndex.value, 1)
  newData.splice(index, 0, removed)
  displayData.value = newData
  
  // 更新排序
  handleNativeDragEnd()
}

const handleNativeDragEnd = () => {
  dragItemIndex.value = null
  isDragging.value = -1
  
  // 创建排序对象数组，包含ID和排序索引
  const newOrder = displayData.value.map((item, index) => ({
    objectId: item.ObjectId,
    sortVal: index + 1
  }))

  console.log('新排序', newOrder)
  
  // 设置排序中状态
  isSorting.value = true
  
  // 调用接口更新排序
  updateHomeCameraOrder(newOrder).then(() => {
    ElMessage.success('排序更新成功')
    initHomeCameraList()
  }).catch(() => {
    ElMessage.error('排序更新失败')
    initHomeCameraList()
  }).finally(() => {
    isSorting.value = false
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 构建提交参数
      const submitData = {
        channelId: form.value.ChannelId,
        orgId: form.value.OrgId,
        configType: ''
      }
      if (powerCode.value === 'childrenOrg') {
        submitData.orgId = userStore.userInfo?.unitId
        submitData.configType = '下级单位'
      } else {
        delete submitData.orgId
        submitData.configType = '总公司'
      }
      
      console.log('提交的数据:', submitData)
      
      // 实现提交逻辑
      if (!isEdit.value) {
        addHomeCamera(submitData).then(res => {
          console.log(res, '==addHomeCamera==')
          ElMessage.success('添加成功')
          formDialogVisible.value = false
          //刷新列表
          initHomeCameraList()
        })
      }
    }
  })
}
</script>

<style lang="scss">
.el-loading-mask {
  background-color: rgba(5, 45, 98, 1) !important;
}
.el-dialog {
  background-color: rgba(5, 45, 98, 1) !important;
  border: 1px solid rgba(5, 45, 98, 1) !important;

  .el-dialog__title,
  .el-form-item__label {
    color: rgba(255,255,255,1);
  }
}

.el-input__wrapper,
.el-select__wrapper {
  background-color: transparent !important;
  border: 1px solid rgb(40, 136, 238) !important;
  box-shadow: none !important;
}

.el-input__inner,
.el-select__placeholder {
  background-color: transparent !important;
  color: rgb(40, 136, 238) !important;
}

.el-input__inner:focus,
.el-select__input:focus {
  border-color: rgba(5, 45, 98, 1) !important;
}

.el-input__inner {
  color: rgb(40, 136, 238) !important;
}
</style>
<style scoped lang="scss">
.video-manage-dialog {
  :deep(.el-select-dropdown__item.is-hovering) {
    background-color: rgb(29, 98, 187) !important;
    color: rgba(255, 255, 255, 0.8) !important;
  }
  :deep(.el-dialog) {
    background-size: 100% 100%;
    border: 1px solid rgb(40, 136, 238);

    .el-dialog__header {
      border-bottom: 1px solid rgba(43, 119, 126, 0.5);
      margin-right: 0;
      padding: 15px 20px;

      .el-dialog__title {
        color: #fff;
        font-size: 16px;
      }
    }

    .el-dialog__body {
      padding: 20px;
      color: #fff;
    }
  }
}

.search-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;

  .search-input {
    width: 300px;
  }
}

.total-text {
  height: 35px;
  line-height: 35px;
  color: rgba(255, 255, 255, 0.8);
}

.draggable-outer-container {
  width: 100%;
  border: 1px solid rgb(21, 81, 159);
  border-radius: 4px;
  background-color: transparent;
}

.custom-scrollbar {
  --el-scrollbar-bg-color: rgba(40, 136, 238, 0.1);
  --el-scrollbar-hover-bg-color: rgba(40, 136, 238, 0.3);
  --el-scrollbar-hover-opacity: 1;
  
  :deep(.el-scrollbar__bar) {
    opacity: 0.3;
    transition: opacity 0.3s;
    
    &:hover {
      opacity: 1;
    }
  }
}

.draggable-list {
  padding: 10px;
}

.draggable-item {
  padding: 5px;
  margin-bottom: 10px;
  background-color: rgba(5, 45, 98, 0.5);
  border-radius: 4px;
  border: 1px solid rgb(21, 81, 159);
  transition: all 0.3s ease;
  color: white;

  &:hover {
    background-color: rgba(40, 136, 238, 0.2);
    
    .drag-handle {
      opacity: 1;
    }
  }

  &.dragging {
    background-color: rgba(40, 136, 238, 0.3);
    border: 1px dashed rgb(40, 136, 238);
  }
  
  &.disabled {
    opacity: 0.7;
    cursor: not-allowed;
    
    &:hover {
      background-color: rgba(5, 45, 98, 0.5);
      
      .drag-handle {
        opacity: 0.3;
        cursor: not-allowed;
      }
    }
  }

  .item-content {
    display: flex;
    align-items: center;
  }

  .drag-handle {
    cursor: move;
    margin-right: 10px;
    opacity: 0.3;
    transition: opacity 0.3s ease;
    
    .el-icon {
      color: rgba(255, 255, 255, 0.8);
      font-size: 16px;
    }
  }

  .item-index {
    width: 60px;
    text-align: center;
  }

  .item-name {
    flex: 1;
    margin-right: 10px;
  }

  .item-org {
    width: 220px;
    margin-right: 10px;
  }

  .item-actions {
    width: 80px;
    text-align: center;
  }
}

.ghost-item {
  opacity: 0.5;
  background: rgba(40, 136, 238, 0.1) !important;
  border: 1px dashed rgb(40, 136, 238) !important;
}

.chosen-item {
  background-color: rgba(40, 136, 238, 0.2) !important;
  border-color: rgb(40, 136, 238) !important;
}

.sorting-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  z-index: 10002;

  .sorting-icon {
    font-size: 40px;
    color: #fff;
    margin-bottom: 10px;
    animation: rotating 2s linear infinite;
  }

  span {
    font-size: 16px;
    color: #fff;
    font-weight: bold;
  }
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
